package org.example.work2.tcc.business.serivce.impl;


import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.example.work2.tcc.business.dto.Account;
import org.example.work2.tcc.business.dto.Business;
import org.example.work2.tcc.business.dto.Order;
import org.example.work2.tcc.business.feign.AccountClient;
import org.example.work2.tcc.business.feign.OrderClient;
import org.example.work2.tcc.business.serivce.BusinessService;
import org.example.work2.tcc.business.utils.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 业务服务导入
 *
 * @author xh
 * @date 2023/04/03
 */

@Slf4j
@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    AccountClient accountClient;

    @Autowired
    OrderClient orderClient;

    @Override
    @GlobalTransactional(name="at-place-order", timeoutMills = 20000, rollbackFor = Exception.class)
    public String placeOrder(Business business) {

        String xId = RootContext.getXID();
        log.info("[placeOrder] 开始下单");
        log.info("[placeOrder] 当前 XID: {}", xId);

        BusinessActionContext businessActionContext = new BusinessActionContext();
        businessActionContext.setXid(xId);

        // 生成订单 ID
        Long orderId = IdUtil.nextId();

        Order order = new Order();
        order.setId(orderId);
        order.setAccountCode(business.getAccountCode());
        order.setProductId(business.getProductId());
        order.setProductCounts(business.getProductCounts());
        Integer totalPrice = business.getPrice() * business.getProductCounts();
        //总积分
        order.setTotalPrice(totalPrice);

        // 创建订单
        boolean createOrder = orderClient.createOrder(businessActionContext, order.getId(), order.getAccountCode(),
                order.getProductId(), order.getProductCounts(), order.getTotalPrice());
        if(!createOrder){
            throw new RuntimeException("下单失败");
        }

        //更新account
        Account account = accountClient.findAccountByCode(business.getAccountCode());
        //检查剩余积分
        if(account.getAccountScores() < totalPrice){
            throw new RuntimeException("账户积分不足");
        }
        boolean updateScores = accountClient.updateScores(businessActionContext, account.getAccountCode(), totalPrice);
        if(!updateScores){
            throw new RuntimeException("更新账户信息失败");
        }


        log.info("[placeOrder] 下单成功, 订单Id: "+ orderId);
        return "Success";
    }
}
